<?php

namespace App\Caches;

use App\Models\SmsSign;
use Illuminate\Support\Facades\Cache;

class SmsSignCache
{
    const CACHE_KEY = 'source-to-sign';

    private static function handleData()
    {
        $data = [];
        $rows = SmsSign::select(['name', 'sources'])->get()->toArray();
        foreach ($rows as $row) {
            foreach ($row['sources'] as $source) {
                $data[$source] = $row['name'];
            }
        }
        return $data;
    }

    public static function set()
    {
        return Cache::put(self::CACHE_KEY, self::handleData());
    }

    /**
     * @return mixed
     */
    public static function get()
    {
        $instance = new self();
        return Cache::rememberForever(self::CACHE_KEY, function() use ($instance) {
            return $instance::handleData();
        });
    }

    public static function getBySourceId($sourceId)
    {
       $cache = self::get();
       return $cache[$sourceId] ?? null;
    }

    /**
     * @return bool
     */
    public static function del()
    {
        return Cache::forget(self::CACHE_KEY);
    }

    public static function reset()
    {
        return self::set();
    }
}
